package com.fufu.datastructure.stack;

/**
 * 基于单向链表实现stack
 * @author: BlcakTiger
 * @date: 2023/2/11 13:03
 * @contact: hsf6661@163.com
 */
public class StackByLinkedList {

    public static void main(String[] args) {
        //创建Stack对象
        StackByLinkedList stack = new StackByLinkedList();
        stack.push(12);
        stack.push("金木研");
        stack.push(12.56);
        stack.push('c');
        stack.push(true);
        stack.iterator();
        stack.pop();
        stack.iterator();
    }

    /**
     * 头节点
     */
    private Node head;

    /**
     * 入栈
     * @param o 入栈的节点
     */
    public void push(Object o){
        if (head==null){
            head = new Node(o);
        }else {
            Node node = new Node(o);
            node.next = head;
            head = node;
        }
    }

    /**
     * 出栈
     */
    public void pop(){
        if (head==null){
            throw new RuntimeException("Stack is empty!");
        }
        head = head.next;
    }

    /**
     * 遍历
     */
    public void iterator(){
        if (head==null){
            throw new RuntimeException("Stack is empty!");
        }
        Node temp = head;
        System.out.print("[");
        while (temp!=null){
            System.out.print(temp.data+" ");
            temp=temp.next;
        }
        System.out.println("]");
    }
}

/**
 * 节点类
 */
class Node{
    /**
     * 数据域
     * 用于保存节点中的数据
     */
    Object data;
    /**
     * next域
     * 用于存放当前节点的下一个节点
     */
    Node next;

    public Node(Object data){
        this.data = data;
    }
}
